package com.aizuda.boot.modules.business.template.controller;


import com.aizuda.boot.modules.business.contract.dto.SingleResponse;
import com.aizuda.boot.modules.common.constant.enums.ResponseCodeEnum;
import com.aizuda.boot.modules.business.template.entity.dto.ContractTemplateAddReqDTO;
import com.aizuda.boot.modules.business.template.entity.dto.ContractTemplateQueryReqDTO;
import com.aizuda.boot.modules.business.template.entity.vo.ContractTemplateDraftListRespDTO;
import com.aizuda.boot.modules.business.template.entity.vo.ContractTemplateRespDTO;
import com.aizuda.boot.modules.business.template.entity.vo.ContractTemplatesByTypeRespDTO;
import com.aizuda.boot.modules.business.template.service.ContractTemplateService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import com.aizuda.boot.modules.business.contract.dto.ContractTypeContentReqDTO;
import com.aizuda.boot.modules.business.contract.entity.vo.ContractFormDataDTO;

/**
 * 合同模版控制器
 */
@Slf4j
@RestController
@RequestMapping("/template")
@Tag(name = "合同模版管理接口")
public class ContractTemplateController {

    @Resource
    private ContractTemplateService contractTemplateService;

    @PostMapping("/add")
    @Operation(summary = "添加，发布或修改合同模版")
    public SingleResponse<Integer> addOrUpdateTemplate(@RequestBody @Validated ContractTemplateAddReqDTO dto) {
        try {
            Integer templateId = contractTemplateService.addOrUpdateTemplate(dto);
            return SingleResponse.of(templateId);
        } catch (Exception e) {
            log.error("添加或修改合同模版失败", e);
            return SingleResponse.failure(ResponseCodeEnum.SHOW_MSG.getCode(), "添加或修改合同模版失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{templateId}")
    @Operation(summary = "删除合同模版")
    public SingleResponse deleteTemplate(
            @PathVariable @Parameter(description = "模版ID") Integer templateId) {
        try {
            contractTemplateService.deleteTemplate(templateId);
            return SingleResponse.success();
        } catch (Exception e) {
            log.error("删除合同模版失败", e);
            return SingleResponse.failure(ResponseCodeEnum.SHOW_MSG.getCode(), "删除合同模版失败: " + e.getMessage());
        }
    }

    @GetMapping("/{templateId}")
    @Operation(summary = "获取合同模版详情")
    public SingleResponse<ContractTemplateRespDTO> getTemplateDetail(
            @PathVariable @Parameter(description = "模版ID") Integer templateId) {
        try {
            ContractTemplateRespDTO template = contractTemplateService.getTemplateDetail(templateId);
            return SingleResponse.of(template);
        } catch (Exception e) {
            log.error("获取合同模版详情失败", e);
            return SingleResponse.failure(ResponseCodeEnum.SHOW_MSG.getCode(), "获取合同模版详情失败: " + e.getMessage());
        }
    }

    @GetMapping("/recent/{employeeId}")
    @Operation(summary = "获取最近使用的合同模版列表")
    public SingleResponse<List<Map<String, Object>>> getRecentTemplates(
            @PathVariable  Long employeeId,
            @RequestParam(required = false) @Parameter(description = "返回数量限制，默认10条") Integer limit) {
        try {
            List<Map<String, Object>> templates = contractTemplateService.getRecentTemplates(employeeId, limit);
            return SingleResponse.of(templates);
        } catch (Exception e) {
            log.error("获取最近使用的合同模版列表失败", e);
            return SingleResponse.failure(ResponseCodeEnum.SHOW_MSG.getCode(), "获取最近使用的合同模版列表失败: " + e.getMessage());
        }
    }

    @GetMapping("/drafts/{employeeId}")
    @Operation(summary = "获取用户的模板草稿列表")
    public SingleResponse<ContractTemplateDraftListRespDTO> getTemplateDraftList(
            @PathVariable @Parameter(description = "员工ID") Long employeeId) {
        try {
            ContractTemplateDraftListRespDTO draftList = contractTemplateService.getTemplateDraftList(employeeId);
            return SingleResponse.of(draftList);
        } catch (Exception e) {
            log.error("获取模板草稿列表失败", e);
            return SingleResponse.failure(ResponseCodeEnum.SHOW_MSG.getCode(), "获取模板草稿列表失败: " + e.getMessage());
        }
    }

    @PostMapping("/list")
    @Operation(summary = "获取合同模版列表（支持按类型查询）")
    public SingleResponse<ContractTemplatesByTypeRespDTO> getTemplateList(@RequestBody @Validated ContractTemplateQueryReqDTO reqDTO) {
        try {
            ContractTemplatesByTypeRespDTO templatesByType;
            if (reqDTO.getContractTypeId() != null) {
                templatesByType = contractTemplateService.getTemplatesByContractTypeId(
                    reqDTO.getContractTypeId(), 
                    reqDTO.getPublisherId(),
                    reqDTO.getEditable(),
                    reqDTO.getKeyword()
                );
            } else {
                templatesByType = contractTemplateService.getAllTemplatesByType(
                    reqDTO.getPublisherId(),
                    reqDTO.getEditable(),
                    reqDTO.getKeyword()
                );
            }
            return SingleResponse.of(templatesByType);
        } catch (IllegalArgumentException e) {
            // 参数错误
            log.warn("查询模版列表参数错误: {}", e.getMessage());
            return SingleResponse.failure(ResponseCodeEnum.BUSINESS_EXCEPTION.getCode(), e.getMessage());
        } catch (Exception e) {
            // 系统错误
            String errorMsg = reqDTO.getContractTypeId() != null 
                ? String.format("根据条件查询模版列表失败，合同类型ID: %d", reqDTO.getContractTypeId())
                : "查询合同模版列表失败";
            log.error(errorMsg, e);
            return SingleResponse.failure(ResponseCodeEnum.SHOW_MSG.getCode(), errorMsg + ": " + e.getMessage());
        }
    }

    @GetMapping("/search")
    @Operation(summary = "根据模版名称模糊搜索合同模版")
    public SingleResponse<ContractTemplatesByTypeRespDTO> searchTemplatesByName(
            @RequestParam @Parameter(description = "模版名称关键字") String keyword) {
        try {
            ContractTemplatesByTypeRespDTO templatesByType = contractTemplateService.searchTemplatesByName(keyword);
            return SingleResponse.of(templatesByType);
        } catch (Exception e) {
            log.error("根据模版名称搜索合同模版失败，关键字: {}", keyword, e);
            return SingleResponse.failure(ResponseCodeEnum.SHOW_MSG.getCode(), "搜索合同模版失败: " + e.getMessage());
        }
    }

    @PostMapping("/content")
    @Operation(summary = "根据合同类型ID获取模板content")
    public SingleResponse<ContractFormDataDTO> getContentByContractType(@RequestBody @Validated ContractTypeContentReqDTO reqDTO) {
        try {
            ContractFormDataDTO content = contractTemplateService.getContentByContractTypeAndDepartment(reqDTO.getContractTypeId());
            return SingleResponse.of(content);
        } catch (Exception e) {
            log.error("获取合同类型模板content失败，合同类型ID: {}", reqDTO.getContractTypeId(), e);
            return SingleResponse.failure(ResponseCodeEnum.SHOW_MSG.getCode(), "获取模板内容失败: " + e.getMessage());
        }
    }
}